const express = require('express');
const Adoption = require('../models/adoption');
const { authMiddleware, adminMiddleware } = require('../middleware/auth');
const { pool } = require('../config/db');

const router = express.Router();

// @route   POST api/adoptions/apply
// @desc    Submit an adoption application
// @access  Private
router.post('/apply', authMiddleware, async (req, res) => {
  try {
    const {
      pet_id,
      reason_for_adoption,
      living_situation,
      previous_pet_experience,
      additional_notes
    } = req.body;

    const applicationData = {
      user_id: req.user.id,
      pet_id,
      reason_for_adoption,
      living_situation,
      previous_pet_experience,
      additional_notes
    };

    const application = await Adoption.createApplication(applicationData);
    res.status(201).json(application);
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ message: err.message });
  }
});

// @route   GET api/adoptions/my-applications
// @desc    Get all applications by the logged-in user
// @access  Private
router.get('/my-applications', authMiddleware, async (req, res) => {
  try {
    const applications = await Adoption.getApplicationsByUser(req.user.id);
    res.json(applications);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/my-pets
// @desc    Get all adopted pets by the logged-in user
// @access  Private
router.get('/my-pets', authMiddleware, async (req, res) => {
  try {
    const adoptions = await Adoption.getUserAdoptions(req.user.id);
    res.json(adoptions);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/applications
// @desc    Get all applications (admin only)
// @access  Private/Admin
router.get('/applications', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const { status, page = 1, limit = 10 } = req.query;
    const result = await Adoption.getAllApplications(status, page, limit);
    res.json(result);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/records
// @desc    Get all adoption records (admin only)
// @access  Private/Admin
router.get('/records', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const result = await Adoption.getAdoptionRecords(page, limit);
    res.json(result);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/applications/:id
// @desc    Get application by ID
// @access  Private
router.get('/applications/:id', authMiddleware, async (req, res) => {
  try {
    const application = await Adoption.getApplicationById(req.params.id);
    
    if (!application) {
      return res.status(404).json({ message: 'Application not found' });
    }
    
    // Only admin or the applicant can view the application
    if (!req.user.is_admin && application.user_id !== req.user.id) {
      return res.status(403).json({ message: 'Not authorized to view this application' });
    }
    
    res.json(application);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/pet/:id
// @desc    Get all applications for a pet (admin only)
// @access  Private/Admin
router.get('/pet/:id', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const applications = await Adoption.getApplicationsByPet(req.params.id);
    res.json(applications);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/adoptions/applications/:id
// @desc    Update application status (admin only)
// @access  Private/Admin
router.put('/applications/:id', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const { status } = req.body;
    
    if (!['pending', 'approved', 'rejected'].includes(status)) {
      return res.status(400).json({ message: 'Invalid status' });
    }
    
    const updatedApplication = await Adoption.updateApplicationStatus(
      req.params.id, 
      status,
      req.user.id
    );
    
    res.json(updatedApplication);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/count
// @desc    获取各状态申请的数量
// @access  私有(管理员)
router.get('/count', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    const { status } = req.query;
    let query = 'SELECT COUNT(*) as count FROM adoption_applications';
    const queryParams = [];
    
    if (status) {
      query += ' WHERE status = ?';
      queryParams.push(status);
    }
    
    const [rows] = await pool.query(query, queryParams);
    res.json({ count: rows[0].count });
  } catch (err) {
    console.error('获取申请数量失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   GET api/adoptions/trends
// @desc    获取最近30天的申请趋势数据
// @access  私有(管理员)
router.get('/trends', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    // 计算30天前的日期
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().substring(0, 10);
    
    // 获取最近30天的申请数据
    const [recentApplications] = await pool.query(
      `SELECT application_date FROM adoption_applications
       WHERE application_date >= ?
       ORDER BY application_date DESC`,
      [thirtyDaysAgoStr]
    );
    
    // 按日期分组统计申请数量
    const applicationsByDate = {};
    const dates = [];
    const counts = [];
    
    // 初始化过去30天的日期
    for (let i = 29; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateString = `${date.getMonth() + 1}/${date.getDate()}`;
      dates.push(dateString);
      applicationsByDate[dateString] = 0;
    }
    
    // 统计每天的申请数量
    recentApplications.forEach(application => {
      const date = new Date(application.application_date);
      const dateString = `${date.getMonth() + 1}/${date.getDate()}`;
      if (applicationsByDate[dateString] !== undefined) {
        applicationsByDate[dateString]++;
      }
    });
    
    // 转换为数组
    dates.forEach(date => {
      counts.push(applicationsByDate[date] || 0);
    });
    
    res.json({
      applicationTrend: {
        dates,
        counts
      }
    });
  } catch (err) {
    console.error('获取申请趋势数据失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 